package com.hupo.dyapp_01.service.Impl;

import com.hupo.dyapp_01.Mapper.UserMapper;
import com.hupo.dyapp_01.entity.User;
import com.hupo.dyapp_01.service.IUserService;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletContext;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserServiceImpl implements IUserService {
    @Resource
    private UserMapper userMapper;

    @Resource
    private ServletContext servletContext;

    @Override
    public void registerOrLogin(User user) {

        // 1. 检查验证码是否存在
        Object captchaObj = servletContext.getAttribute(user.getEmail());
        if (captchaObj == null) {
            throw new RuntimeException("请先获取验证码");
        }

        // 2. 验证码比较（转为字符串比较）
        String storedCaptcha = captchaObj.toString();
        if (!storedCaptcha.equals(user.getPassword())) {
            throw new RuntimeException("验证码错误");
        }

        // 3. 检查用户是否存在（修正逻辑）
        User existingUser = userMapper.selectByEmail(user.getEmail());
        if (existingUser == null) {
            // 新用户注册（设置默认值）
            user.setNickname("用户" + System.currentTimeMillis() % 10000);
            user.setAvatarUrl("");
            user.setGender(0);
            user.setAge(0);
            userMapper.insert(user);
        }

        // 4. 清理已使用的验证码（重要！）
        servletContext.removeAttribute(user.getEmail());
    }

    @Override
    public void updateUser(User user) {
        // 1. 根据email查询用户
        User existingUser = userMapper.selectByEmail(user.getEmail());
        if (existingUser == null) {
            throw new RuntimeException("用户不存在");
        }

        // 2. 只更新允许修改的字段
        if (user.getNickname() != null && !user.getNickname().isEmpty()) {
            existingUser.setNickname(user.getNickname());
        }
        if (user.getAvatarUrl() != null && !user.getAvatarUrl().isEmpty()) {
            existingUser.setAvatarUrl(user.getAvatarUrl());
        }
        existingUser.setGender(user.getGender());

        // 3. 执行更新
        userMapper.updateByEmail(existingUser);
    }

    @Override
    public User getUser(String email) {
        return userMapper.selectByEmail(email);
    }
}
